//
// Created by ttai on 2021/12/20.
//

//
// Created by ttai on 2021/12/16.
//

#include "BitOperation.h"

int get_l(string m) {
    return m.size() * 8;
}


string string_bin(string m) {

    string m_hex = string_hex(m);
    string str = "";
    for (int i = 0; i < m_hex.size(); i++) {
        string s(1, m_hex[i]);
        int r = stoi(s, nullptr, 16);
        bitset<4> bit(r);
        str += bit.to_string();
    }
    return str;
}


string string_hex(string m) {
    string strSha1 = "";

    unsigned int c = 0;

    int nLen = m.size();

    for (int i = 0; i < nLen; i++) {
        // 查看md一个字节里的信息
        unsigned int x = 0;
        c = (m[i] >> 4) & 0x0f;
        strSha1 += hex_chars[c];
        x = m[i] & 0x0f;
        strSha1 += hex_chars[x];
    }

    return strSha1;
}


string bin_hex(string bin) {
    string hex = "";
    for (int i = 0; i < bin.size(); i += 4) {
        string tmp = bin.substr(i, 4);
        int r = stoi(tmp, nullptr, 2);
        hex += hex_chars[r];
    }
    return hex;
}

string hex_bin(string hex) {
    string bin = "";
    for (int i = 0; i < hex.size(); i++) {
        string tmp(1, hex[i]);
        bitset<4> bit(stoi(tmp, nullptr, 16));
        bin += bit.to_string();
    }
    return bin;
}


bitset<32> CROL32(bitset<32> bit, int num) {
    if (num >= 32)num -= 32;
    bitset<32> tmp1 = bit << num;
    bitset<32> tmp2 = bit >> (32 - num);
    return tmp1 ^ tmp2;
}

bitset<32> add_32(bitset<32> bit1, bitset<32> bit2) {
    unsigned long long tmp1 = bit1.to_ullong();
    unsigned long long tmp2 = bit2.to_ullong();
    bitset<32> b("11111111111111111111111111111111");
    unsigned long long t = b.to_ullong() + 1;
    unsigned long long ret = (tmp1 + tmp2) % t;
    bitset<32> result(ret);
    return result;
}

string bin_string(string m) {
//    m = m.substr(0,len);
    string str = "";
    for (int i = 0; i < m.size(); i += 8) {
        string tmp = m.substr(i, 8);
        int r = stoi(tmp, nullptr, 2);
        if(r==0)
        {
            str+='\0';
            break;
        }
        str += (char) r;
    }
    return str;
}

string hex_string(string m) {
//    m = m.substr(0,len);
    string str = "";
    for (int i = 0; i < m.size(); i += 2) {
        string tmp = m.substr(i, 2);
        int r = stoi(tmp, nullptr, 16);
        if(r==0)
        {
            str+='\0';
            break;
        }
        str += (char) r;
    }
    return str;
}
